package com.study.demo.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.study.demo.config.JwtConfig;
import com.study.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created on 2019/9/19.
 *
 * @author Grak
 * @since 1.0
 */
@Service
public class TokenService {

    @Autowired
    private JwtConfig jwtConfig ;

    public String getToken(User user) {
        Date date = new Date(System.currentTimeMillis() + jwtConfig.getTimeOut());
        String token = JWT.create().withAudience(user.getId())// 将 user id 保存到 token 里面
                .withExpiresAt(date)
                .sign(Algorithm.HMAC256(user.getPassword() + jwtConfig.getSecret()));// 以 password 作为 token 的密钥
        return token;
    }
}
